package com.repairsystem.repairsys.service.impl;

import com.repairsystem.repairsys.common.ResponseCode;
import com.repairsystem.repairsys.common.ServerResponse;
import com.repairsystem.repairsys.dao.FaultMapper;
import com.repairsystem.repairsys.dao.UserMapper;
import com.repairsystem.repairsys.pojo.Fault;
import com.repairsystem.repairsys.pojo.User;
import com.repairsystem.repairsys.service.IMailService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service("iMailService")
@EnableAspectJAutoProxy(exposeProxy = true)
public class MailServiceImpl implements IMailService {

    @Autowired
    private JavaMailSender mailSender; //框架自带的
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FaultMapper faultMapper;

    @Value("${spring.mail.username}")  //发送人的邮箱
    private String from;

    @Async  //意思是异步调用这个方法
    public void sendMail(String title, String url, String email) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from); // 发送人的邮箱
        message.setSubject(title); //标题
        message.setTo(url); //发给谁  对方邮箱
        message.setText(email); //内容
        mailSender.send(message); //发送
    }

    @Override
    public ServerResponse sendEmail(String userId,String cause) {
        if (!StringUtils.isNotBlank(userId)){
            return ServerResponse.createByErrorCodeMassage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),"参数错误");
        }
        User user = userMapper.selectByPrimaryKey(Long.parseLong(userId));
        if(user == null){
            return ServerResponse.createByErrorMassage("操作异常");
        }
        String  url = user.getUserEmail();
        String title = "成都大学电子设备维修系统";
        String email = "您的订单已被管理员拒绝，原因如下："+cause;
        sendMail(title,url,email);
        return ServerResponse.createBySuccess();
    }
}